
package com.hbu.housingbrokerug.activities;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;

import com.fedorvlasov.lazylist.LazyAdapter;
import com.hbu.housingbrokeruganda.Parser.JSONParser;
import com.hbu.imagePackage.BaseActivity;
import com.hub.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * @author Lubwama Samuel(lubwamasamuel3[at]gmail[dot]com)
 */
@SuppressWarnings("deprecation")
public class Main extends BaseActivity {
	private ProgressDialog pDialog;
	ListView list;
	Gallery gallery;
	LazyAdapter adapter;
	String result = "";
	int arraysize;
	JSONParser jParser = new JSONParser();

	parserFromUrl parser = new parserFromUrl();

	public String[][] IMAGES;

	DisplayImageOptions options = parser.getOptions();
	public String ipOrDomain = parser.getIpOrDomain();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		IMAGES = new String[][] {};
		
		new getAllHousingUnitInformation().execute();

	}

	@Override
	public void onBackPressed() {
		Main.this.finish();
		return;
	}

	public void onDestroy() {
		try {
			list.setAdapter(null);
		} catch (Exception e) {

		}
		super.onDestroy();
	}

	private void startingSingleUnit(int position) {

		Intent intent = new Intent(getApplicationContext(), SingleUnit.class);
		intent.putExtra("UNIT_ID", IMAGES[position][0]);
		intent.putExtra("UNIT_DISTRICT", IMAGES[position][2]);
		intent.putExtra("UNIT_CITY", IMAGES[position][3]);
		intent.putExtra("UNIT_TOWN", IMAGES[position][4]);
		intent.putExtra("UNIT_VILLAGE", IMAGES[position][5]);
		intent.putExtra("UNIT_LATITUDE", IMAGES[position][6]);
		intent.putExtra("UNIT_LONGITUDE", IMAGES[position][7]);
		intent.putExtra("UNIT_CATEGORY", IMAGES[position][8]);
		intent.putExtra("UNIT_COST", IMAGES[position][9]);
		intent.putExtra("LANDLORD_FIRSTNAME", IMAGES[position][10]);
		intent.putExtra("LANDLORD_LASTNAME", IMAGES[position][11]);
		intent.putExtra("CONTACTS", IMAGES[position][12]);
		startActivityForResult(intent, 100);

	}

	private class ImageGalleryAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return IMAGES.length;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		// Images to the Upper Gallery
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = (ImageView) convertView;
			if (imageView == null) {
				imageView = (ImageView) getLayoutInflater().inflate(
						R.layout.item_gallery_image, parent, false);
			}
			imageLoader.displayImage(IMAGES[position][1], imageView, options);
			return imageView;
		}
	}

	public class getAllHousingUnitInformation extends
			AsyncTask<String, String, String> {
		JSONParser urlRequest=new JSONParser();
		Bundle bundle=getIntent().getExtras();
		
		public getAllHousingUnitInformation() {

		}

		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Main.this);
			pDialog.setMessage("Loading Houses From Server. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			final String TAG_SUCCESS = "success";
			final String HOUSING_UNIT = "housing_units";
			
			String category="1";
					category=bundle.getString("CATEGORY_ID");
			
					JSONObject json = jParser
					.makeHttpRequest((parser.getIpOrDomain() + parser
							.getQueryFile()).toString(), "GET", parser
							.getParametersAllHousingUnits(category));
			Log.d("PARAMERER NAME", params.toString());
			try {
				int success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					JSONArray jArray = json.getJSONArray(HOUSING_UNIT);
					IMAGES = new String[jArray.length()][13];
					for (int i = 0; i < jArray.length(); i++) {
						JSONObject json1 = jArray.getJSONObject(i);
						/* 1 */IMAGES[i][0] = json1.getString("unit_id");
						/* 2 */IMAGES[i][1] = parser.getIpOrDomain()
								+ json1.getString("urls_image");
						/* 3 */IMAGES[i][2] = json1.getString("district");
						/* 4 */IMAGES[i][3] = json1.getString("city");
						/* 5 */IMAGES[i][4] = json1.getString("town");
						/* 6 */IMAGES[i][5] = json1.getString("village");
						/* 7 */IMAGES[i][6] = json1.getString("latitude");
						/* 8 */IMAGES[i][7] = json1.getString("longitude");
						/* 9 */IMAGES[i][8] = json1.getString("unit_category");
						// Log.d("", IMAGES[i][8]);
						/* 10 */IMAGES[i][9] = json1.getString("cost");
						/* 11 */IMAGES[i][10] = json1.getString("last_name");
						/* 12 */IMAGES[i][11] = json1.getString("first_name");
						/* 13 */IMAGES[i][12] = json1.getString("phone");
					}

				} else if (success == 0) {
					IMAGES = new String[1][1];
					IMAGES[0][0] = "No Data";
				} else if (success == 3) {

					IMAGES = new String[1][1];
					IMAGES[0][0] = "No Results";
				}
			} catch (Exception e) {
				Log.e("FAILED TO PASS DATA", e.toString());

			}
			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					Log.d("DATA TRIAL", String.valueOf(IMAGES.length));
					if (IMAGES[0][0] != "No Data"
							&& IMAGES[0][0] != "No Results") {
						list = (ListView) findViewById(R.id.listViewAllunits);
						adapter = new LazyAdapter(Main.this, IMAGES, ipOrDomain);
						list.setAdapter(adapter);
						list.setItemsCanFocus(true);
						list.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								startingSingleUnit(position);
							}
						});
						gallery = (Gallery) findViewById(R.id.gallery1);
						gallery.setAdapter(new ImageGalleryAdapter());
						gallery.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								startingSingleUnit(position);
							}
						});
					} else {

						if (IMAGES[0][0] == "No Data") {
							AlertDialog alert = new AlertDialog.Builder(
									Main.this).create();
							alert.setTitle("Internet Reach Faluire Error");
							alert.setMessage("Failed To Connect To Server Check Your Internet Setting or Check If You have Data");
							alert.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											// closing the application
											finish();
										}
									});
							alert.show();
						} else if (IMAGES[0][0] == "No Results") {
							AlertDialog alert = new AlertDialog.Builder(
									Main.this).create();
							alert.setTitle("We are Embaraced");
							alert.setMessage("No "+bundle.getString("CATEGORY_NAME")+" Available \n Try Again Later");
							alert.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											finish();
										}
									});
							alert.show();

						}
					}
				}
			});
		}
	}
}